#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
using namespace std;
#define CONV(TYPE) (sockaddr*)(TYPE)
//最大的连接数
#define BACKLOG 8 
class udp_server
{
public:
    udp_server(uint16_t port = 8080)
        :_port(port)
    {

    }
    void Init(){
        _fd = socket(AF_INET,SOCK_STREAM,0);
        if (_fd < 0){
            cerr << "socket create error" << endl;
            exit(-1);
        }
        //bind操作
        sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = ::htons(_port); //把本地字节序列转化为网络字节序列
        local.sin_addr.s_addr = INADDR_ANY; //指的是这个服务器接受来则任何ip的ip访问
        socklen_t len = sizeof(local);

        if(::bind(_fd,CONV(&local),len) < 0){
            cerr << "bind error" << endl;
            exit(-1);
        }
        if (listen(_fd,BACKLOG) < 0){
            cerr << "listen error" << endl;
            exit(1);
        }
        cout << "server 初始化成功" << endl;
    }
    void Start(){
        while(true){
            sockaddr_in peer;
            memset(&peer,0,sizeof(peer));
            socklen_t Len = sizeof(peer);  
            cout << "wait accept" << endl;
            int socketfd = accept(_fd,(struct sockaddr*)(&peer),&Len);       
            if (socketfd < 0){
                cout << "accept error" << endl;
                exit(-1);
            }   
            cout << "accept success, fd is" << socketfd << endl;
            while(1){
                cout << "开始IO" << endl;
                char buffer[1024];
                int n = ::recv(socketfd,buffer,sizeof(buffer)-1,0);
                if (n > 0){
                string client = "echo server say# ";
                buffer[n] = 0;
                client += buffer;
                char Ip[64];
                ::inet_ntop(AF_INET,&(peer.sin_addr),Ip,64);
                std::string ip = Ip;
                string port = to_string(::ntohs(peer.sin_port));
                cout  << ip << ":" << port << "say#" << buffer << "[tcp server message]" << endl;
                send(socketfd,client.c_str(),client.size(),0);
                }
                else if(n == 0){
                    cout << "client quit" << endl;
                    break;
                }
                else {
                    return;
                }
            }
           
        }
    }
    ~udp_server(){
        ::close(_fd);
    }
private:
    int _fd;
    uint16_t _port;
};

void Useage(const string& message){
    cout << "Useage: " << message << "+  serverport" << endl;
}
int main(int argc,char* argv[]){
    if (argc != 2){
        Useage(argv[0]);
        exit(1);
    }
    uint16_t serverport = stoi(argv[1]);
    udp_server us(serverport);
    us.Init();
    us.Start();
    return 0;
}